import 'dart:convert';

import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/location_repository/location_repository.dart';
import 'package:e_reception_flutter/singleton/location_repository/vo/area_data.dart';
import 'package:e_reception_flutter/singleton/location_repository/vo/location_data.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_enum.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/choose_city/utils/choose_city_utils.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import 'choose_city_place_list_widget.dart';

/// 选择城市-tab栏和页
///
/// @author: zengxiangxi
/// @createTime: 1/9/21 2:31 PM
/// @specialDemand: 编写逻辑过于复杂
class ChooseCityTabsAndPagesWidget extends StatefulWidget {
  ///1-3级
  final int subLevel;

  final ValueChanged<Map<String, ChooseCityListItemBean>> selectedFunc;

  Map<String, ChooseCityListItemBean> selected;

  final ValueNotifier<String> cityNameValueNotifier;
  final bool lightTheme;

  ChooseCityTabsAndPagesWidget(
      {Key key, this.subLevel, this.selectedFunc, this.selected, this.cityNameValueNotifier, this.lightTheme})
      : assert(subLevel != null && subLevel >= 1 && subLevel <= 3),
        assert(selectedFunc != null),
        super(key: key);

  @override
  _ChooseCityTabsAndPagesWidgetState createState() =>
      _ChooseCityTabsAndPagesWidgetState();
}

class _ChooseCityTabsAndPagesWidgetState
    extends State<ChooseCityTabsAndPagesWidget> with TickerProviderStateMixin {
  TabController _tabController;

  List<ChooseCityEnum> _tabsList = List();

  List<ChooseCityListItemBean> _provinceList;

  List<ChooseCityListItemBean> _cityList;

  List<ChooseCityListItemBean> _districtList;

  ///选中省份
  ChooseCityListItemBean _selectedProvinceBean;

  ///选中城市
  ChooseCityListItemBean _selectedCityBean;

  ///选中区县
  ChooseCityListItemBean _selectedDistrictBean;

  // List<ChooseCityListItemBean> citySearchList=List<ChooseCityListItemBean>();

  // ValueNotifier<List<String>> searchCityNameList;

  @override
  void initState() {
    super.initState();
    // searchCityNameList = ValueNotifier<List<String>>(null);
        _provinceList = ChooseCityUtils.getProvinceList();
    for (int i = 0; i < widget.subLevel; i++) {
      _tabsList?.add(ChooseCityEnum.values.elementAt(i));
    }
    _tabController = TabController(length: _tabsList?.length ?? 0, vsync: this);
    _initJump();
    // Future.delayed(Duration.zero, () {
    //   _initJump();
    // });
      widget?.cityNameValueNotifier?.addListener(() {
        if(widget?.cityNameValueNotifier?.value!=null){
          init();
        }
      });
  }


  init() {
    /**
     * 1.根据省市区字符串查询
     * 2.根据查询出得结果循环获取到
     */
    List<Map<String,ChooseCityListItemBean>> strListName = List<Map<String,ChooseCityListItemBean>>();
    LocationData _allLocationData = LocationRepository.getInstance().allLocationData();
    _allLocationData?.list?.forEach((element) {
        element?.city?.forEach((cityName) {
          if(cityName?.sname?.contains(widget?.cityNameValueNotifier?.value??"")){
            cityName?.site?.forEach((siteName) {
                Map<String, ChooseCityListItemBean> resultMap = {
                  CHOOSE_PROVINCE_KEY: ChooseCityListItemBean(element?.sid,element?.sname, latitude: element?.la, longitude: element?.lo),
                  CHOOSE_CITY_KEY: ChooseCityListItemBean(cityName?.sid,cityName?.sname, latitude: cityName?.la, longitude: cityName?.lo),
                  CHOOSE_DISTRICT_KEY: ChooseCityListItemBean(siteName?.sid,siteName?.sname, latitude: siteName?.la, longitude: siteName?.lo),
                };
                strListName?.add(resultMap);
            });
          }
          cityName?.site?.forEach((siteName) {
            if(siteName?.sname?.contains(widget?.cityNameValueNotifier?.value??"")){
              Map<String, ChooseCityListItemBean> resultMap = {
                CHOOSE_PROVINCE_KEY: ChooseCityListItemBean(element?.sid,element?.sname, latitude: element?.la, longitude: element?.lo),
                CHOOSE_CITY_KEY: ChooseCityListItemBean(cityName?.sid,cityName?.sname, latitude: cityName?.la, longitude: cityName?.lo),
                CHOOSE_DISTRICT_KEY: ChooseCityListItemBean(siteName?.sid,siteName?.sname, latitude: siteName?.la, longitude: siteName?.lo)
              };
              strListName?.add(resultMap);
            }
          });
        });
    });
    if(strListName?.length!=0){
      VgEventBus.global.send(SearchCityNameListEventMonitor(strListName));
    }
    // searchCityNameList?.value = strListName;
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _toTabThemeWidget(),
        Expanded(
          child: _toTabBarViewWidget(),
        )
      ],
    );
  }

  Widget _toTabThemeWidget() {
    return Container(
      height: 45,
      color: (widget?.lightTheme??false)?Colors.white:null,
      child: ScrollConfiguration(
          behavior: MyBehavior(),
          child: Theme(
              data: ThemeData(
                  highlightColor: Colors.transparent,
                  splashColor: Colors.transparent),
              child: _toTabBarWidget())),
    );
  }

  Widget _toTabBarWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      child: TabBar(
        controller: _tabController,
        isScrollable: true,
        indicatorSize: TabBarIndicatorSize.label,
        unselectedLabelStyle: TextStyle(
            color: (widget?.lightTheme??false)?Color(0xFF8B93A5):ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
            fontSize: 13,
            height: 1.2),
        labelStyle: TextStyle(
            color: (widget?.lightTheme??false)?ThemeRepository.getInstance().getCardBgColor_21263C():ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
            fontSize: 13,
            fontWeight: FontWeight.w600,
            height: 1.2),
        indicatorColor: (widget?.lightTheme??false)?ThemeRepository.getInstance().getCardBgColor_21263C():ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        indicatorPadding: EdgeInsets.only(left: 6, right: 6),
        tabs: List.generate(_tabsList?.length ?? 0, (index) {
          bool isShowTab;
          switch (_tabsList?.elementAt(index)) {
            case ChooseCityEnum.province:
              isShowTab = true;
              break;
            case ChooseCityEnum.city:
              isShowTab = _selectedProvinceBean != null;
              break;
            case ChooseCityEnum.district:
              isShowTab = _selectedCityBean != null;
              break;
            default:
              isShowTab = true;
          }
          return Offstage(
            offstage: !isShowTab,
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 5),
              child: Text(_tabsList?.elementAt(index)?.toStr(), style: TextStyle(color: (widget?.lightTheme??false)?ThemeRepository.getInstance().getCardBgColor_21263C():ThemeRepository.getInstance().getTextMinorGreyColor_808388()),),
            ),
          );
        }),
      ),
    );
  }

  Widget _toTabBarViewWidget() {
    return ScrollConfiguration(
      behavior: MyBehavior(),
      child: TabBarView(
          controller: _tabController,
          physics: NeverScrollableScrollPhysics(),
          children: _getPageWidgetList() ?? []),
    );
  }

  List<Widget> _getPageWidgetList() {
    int tabLength = _tabsList?.length ?? 0;
    switch (tabLength) {
      case 1:
        return [_getProvinceListWidget()];
      case 2:
        return [_getProvinceListWidget(), _getCityListWidget()];
      case 3:
        return [
          _getProvinceListWidget(),
          _getCityListWidget(),
          _getDistrictWidget()
        ];
    }
    return null;
  }

  ChooseCityPlaceListWidget _getProvinceListWidget() {
    return ChooseCityPlaceListWidget(
        list: _provinceList,
        selectedBean: _selectedProvinceBean,
        lightTheme: (widget?.lightTheme??false),
        onSelectedFunc: (ChooseCityListItemBean itemBean) {
          if (itemBean == null) {
            VgToastUtils.toast(
                context, "选择${ChooseCityEnum.province.toStr()}异常");
            return;
          }
          _selectedProvinceBean = itemBean;
          _selectedCityBean = null;
          _selectedDistrictBean = null;
          if ((_tabsList?.length ?? 0) == 1) {
            setState(() {});
            _popResult();
            return;
          }
          _processGetListAndJump(ChooseCityEnum.province);
        });
  }

  ChooseCityPlaceListWidget _getCityListWidget() {
    return ChooseCityPlaceListWidget(
        list: _cityList,
        selectedBean: _selectedCityBean,
        lightTheme: (widget?.lightTheme??false),
        onSelectedFunc: (ChooseCityListItemBean itemBean) {
          if (itemBean == null) {
            VgToastUtils.toast(context, "选择${ChooseCityEnum.city.toStr()}异常");
            return;
          }
          _selectedCityBean = itemBean;
          _selectedDistrictBean = null;
          if(_selectedProvinceBean.sname == "台湾"
              || _selectedProvinceBean.sname == "香港特别行政区"
              || _selectedProvinceBean.sname == "澳门特别行政区"
          ){
            _popResult();
            return;
          }
          if ((_tabsList?.length ?? 0) == 2) {
            setState(() {});
            _popResult();
            return;
          }
          _processGetListAndJump(ChooseCityEnum.city);
        });
  }

  ChooseCityPlaceListWidget _getDistrictWidget() {
    return ChooseCityPlaceListWidget(
      list: _districtList,
      selectedBean: _selectedDistrictBean,
      lightTheme: (widget?.lightTheme??false),
      onSelectedFunc: (ChooseCityListItemBean itemBean) {
        if (itemBean == null) {
          VgToastUtils.toast(context, "选择${ChooseCityEnum.district.toStr()}异常");
          return;
        }
        _selectedDistrictBean = itemBean;
        setState(() {});
        _popResult();
      },
    );
  }

  void _popResult() {
    if (widget?.selectedFunc == null) {
      return;
    }
    Map<String, ChooseCityListItemBean> resultMap;
    if(_selectedDistrictBean != null){
      resultMap = {
        CHOOSE_PROVINCE_KEY: _selectedProvinceBean,
        CHOOSE_CITY_KEY: _selectedCityBean,
        CHOOSE_DISTRICT_KEY: _selectedDistrictBean
      };
    }else{
      resultMap = {
        CHOOSE_PROVINCE_KEY: _selectedProvinceBean,
        CHOOSE_CITY_KEY: _selectedCityBean,
      };
    }
    widget?.selectedFunc(resultMap);
  }

  void _processGetListAndJump(ChooseCityEnum type) {
    if (type == null) {
      return;
    }
    switch (type) {
      case ChooseCityEnum.province:
        _cityList = ChooseCityUtils.getCityList(_selectedProvinceBean?.sid);
        _districtList=null;
        _selectedCityBean=null;
        _selectedDistrictBean=null;
        setState(() {
          Future.delayed(Duration(milliseconds: 100)).then((value) =>
              _tabController.animateTo(ChooseCityEnum.city.index,
                  duration: DEFAULT_ANIM_DURATION));
        });

        return;
      case ChooseCityEnum.city:
        _cityList = ChooseCityUtils.getCityList(_selectedProvinceBean?.sid);
        _districtList = ChooseCityUtils.getDistrictList(
            _selectedProvinceBean?.sid, _selectedCityBean?.sid);
        setState(() {
          Future.delayed(Duration(milliseconds: 100)).then((value) =>
              _tabController.animateTo(ChooseCityEnum.district.index,
                  duration: DEFAULT_ANIM_DURATION));

        });

        return;
    }
  }

  void _initJump() {
    if (widget?.selected == null || widget.selected.isEmpty) {
      return;
    }
    _selectedProvinceBean = widget.selected[CHOOSE_PROVINCE_KEY];
    _selectedCityBean = widget.selected[CHOOSE_CITY_KEY];
    _selectedDistrictBean = widget.selected[CHOOSE_DISTRICT_KEY];

    int maxTabLength = _tabsList?.length ?? 0;
    if (_selectedProvinceBean == null) {
      return;
    }
    if (_selectedDistrictBean != null && maxTabLength >= 3) {
      setState(() {
        _cityList = ChooseCityUtils.getCityList(_selectedProvinceBean?.sid);
        _districtList = ChooseCityUtils.getDistrictList(
            _selectedProvinceBean?.sid, _selectedCityBean?.sid);
        _tabController.animateTo(ChooseCityEnum.district.index,
            duration: DEFAULT_ANIM_DURATION);
      });

      return;
    }
    if (_selectedCityBean != null && maxTabLength >= 2) {
      setState(() {
        _cityList = ChooseCityUtils.getCityList(_selectedProvinceBean?.sid);
        _tabController.animateTo(ChooseCityEnum.city.index,
            duration: DEFAULT_ANIM_DURATION);
      });
      return;
    }
  }
}
